<template>
  <section>
    <!-- 操作 -->
    <el-col :span="24" style="margin-bottom: 10px">
      <el-button type="primary" @click="handleAdd">新增</el-button>
    </el-col>

    <!--列表-->
    <el-table :data="tableData" highlight-current-row border
              v-loading="listLoading" style="width: 100%;">
      <el-table-column type="selection" width="55">
      </el-table-column>
      <el-table-column prop="name" label="姓名" width="120" >
      </el-table-column>
      <el-table-column prop="email" label="邮件" >
      </el-table-column>
      <el-table-column prop="phone" label="手机号码" width="130" >
      </el-table-column>
      <el-table-column prop="birthday" label="生日" width="180" >
      </el-table-column>
      <el-table-column label="操作" width="220">
        <template slot-scope="scope">
          <el-button  @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!--工具条-->
    <el-col :span="24" class="toolbar">
      <el-pagination
        :current-page="currentPage"
        :page-size="pageSize"
        layout="total,sizes,prev, pager, next, jumper"
        :total="total" style="float: right">
      </el-pagination>
    </el-col>

    <!-- 弹窗 -->
    <el-dialog :title="dialogTitle" size="tiny" :visible.sync="myFormVisible" :close-on-click-modal="false">
      <el-form :model="myForm" :rules="rules" label-width="80px" ref="myForm">
        <el-form-item label="地址选择" prop="options">
          <address-select v-model="myForm.options"></address-select>
        </el-form-item>
        <el-form-item label="别名" prop="alias">
          <el-input v-model="myForm.alias" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="姓名" prop="name">
          <el-input v-model="myForm.name" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="myForm.password" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="邮件" prop="email">
          <el-input v-model="myForm.email" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="手机" prop="phone">
          <el-input v-model="myForm.phone" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="生日" prop="birthday">
          <el-date-picker type="date" placeholder="选择日期" v-model="myForm.birthday"></el-date-picker>
        </el-form-item>
        <el-form-item label="日期范围" prop="mydaterange">
          <el-date-picker type="daterange" placeholder="选择日期" v-model="myForm.mydaterange"></el-date-picker>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click.native="myFormVisible = false">取消</el-button>
        <el-button type="primary" @click.native="handleSubmit" :loading="submitLoading">提交</el-button>
      </div>
    </el-dialog>
  </section>
</template>

<script>
  import { getPartners, savePartners } from '../../api/system/partner';

  export default {
    data () {
      return {
        dialogTitle: '新增',
        tableData: [],
        total: 0,
        currentPage: 1,
        pageSize: 10,
        sortProp: null,
        sortOrder: 'ascending',
        listLoading: false,
        myFormVisible: false,
        submitLoading: false,
        // 表单数据
        myForm: {
          options: [],
          addressId: null,
          addressIds: null,
          'id': null,
          'password': null,
          'alias': null,
          'email': null,
          'name': null,
          'phone': null,
          'sex': null,
          'status': null,
          'type': null,
          birthday: null,
          // 后台对应表mydate1字段
          mydate1: null,
          // 后台对应表mydate2字段
          mydate2: null,
          // 不是后台字段的日期范围
          mydaterange: []
        },
        // 验证规则
        rules: {
          options: [
            {type: 'array', required: true, message: '请输入活动名称', trigger: 'change'}
          ],
          name: [
            {required: true, message: '请输入姓名', trigger: 'blur'},
            {min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur'}
          ],
          alias: [
            {required: true, message: '请输入别名', trigger: 'blur'},
            {min: 3, max: 15, message: '长度在 3 到 15 个字符', trigger: 'blur'}
          ],
          email: [
            {required: true, message: '请输入邮件', trigger: 'blur'},
            {min: 3, max: 15, message: '长度在 3 到 15 个字符', trigger: 'blur'}
          ],
          phone: [
            {required: true, message: '请输入手机号码', trigger: 'blur'}
          ]
        }
      };
    },
    watch: {
      'myForm.mydaterange': {
        handler (val) {
          this.myForm.mydate1 = val[0] == null ? null : val[0].toJSON();
          this.myForm.mydate2 = val[1] == null ? null : val[1].toJSON();
        },
        deep: true
      },
      'myForm.options': {
        handler (val) {
          this.myForm.addressId = val.length ? val[val.length - 1] : null;
          this.myForm.addressIds = val.join(',');
        },
        deep: true
      }
    },
    methods: {
      // 弹出修改窗口
      handleEdit (index, row) {
        this.resetForm();
        this.dialogTitle = '修改';
        this.myFormVisible = true;
        this.myForm = Object.assign({
          // 模拟
          birthday: null,
          mydate1: null,
          mydate2: null,
          mydaterange: []
        }, row);
        // 模拟日期范围回填
        this.myForm.mydate1 = new Date();
        this.myForm.mydate2 = new Date();
        this.myForm.mydate2.setDate(22);
        this.myForm.mydaterange = [row.mydate1, row.mydate2];
        // 模拟地址回填
        this.myForm.addressId = 110101;
        this.myForm.addressIds = '110000,110100,110101';
        this.myForm.options = '110000,110100,110101'.split(',').map(item => parseInt(item));
      },
      // 新增修改数据提交
      handleSubmit () {
        console.log(this.myForm);
        // 表单验证
        this.$refs['myForm'].validate((valid) => {
          if (valid) {
            this.submitLoading = true;
            savePartners('xxx', this.myForm).then((res) => {
              this.submitLoading = false;
              if (res.data.successFlg === true) {
                this.myFormVisible = false;
                this.getTableData();
              } else {
                this.$message.error(res.data.errorMsg);
              }
            }).catch(function (error) {
              console.log(error);
            });
          } else {
            console.log('error submit!!');
            return false;
          }
        });
      },
      // 重置表单
      resetForm () {
        if (this.$refs.myForm) {
          this.$refs.myForm.resetFields();
        }
        // 当先点击修改，再点击新增，会出现值没有清空,修复处理
        for (let p in this.myForm) {
          if (this.myForm[p] instanceof Array) {
            this.myForm[p] = [];
          } else {
            this.myForm[p] = null;
          }
        }
      },
      // 弹出添加窗体
      handleAdd () {
        this.dialogTitle = '新增';
        this.resetForm();
        this.myFormVisible = true;
      },
      // 获取表格数据
      getTableData () {
        console.log('token:', this.$store.state.token);
        let str = [];
        for (let p in this.condition) {
          if (this.condition[p] !== '' && this.condition[p] !== null) {
            str.push(p + '=' + this.condition[p]);
          }
        }
        this.listLoading = true;
        getPartners({
          page: this.currentPage,
          size: this.pageSize,
          filters: str.join(';'),
          sorts: (this.sortProp === null ? '' : (this.sortOrder === 'ascending' ? '-' : '+') + this.sortProp)
        }).then((res) => {
          if (res.data.successFlg === true) {
            this.tableData = res.data.detailModelList;
            this.currentPage = res.data.currPage;
            this.total = res.data.totalCount;
            this.pageSize = res.data.pageSize;
            this.listLoading = false;
          } else {
            this.$message.error(res.data.errorMsg);
          }
        });
      }
    },
    // 初始化数据
    mounted () {
      this.getTableData();
    }
  };
</script>

<style lang="less">

</style>
